class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for(int i = 0;i < n;) {
            long tmp = (long)target - nums[i];
            for(int j = i + 1;j < n;) {
                long tmp1 = tmp - nums[j];
                int left = j + 1;
                int right = n - 1;
                while(left < right) {
                    int sum = nums[left] + nums[right];
                    if(sum < tmp1) left++;
                    else if(sum > tmp1) right--;
                    else {
                        list.add(new ArrayList<>(Arrays.asList(nums[i],nums[j],nums[left],nums[right])));
                        left++;right--;
                        while(left < right && nums[left] == nums[left - 1]) left++;
                        while(left < right && nums[right] == nums[right + 1]) right--;
                    }
                }
                j++;
                while(j < n && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while(i < n && nums[i] == nums[i - 1]) i++;
        }
        return list;
    }
}